package com.hqq.servive.impl;

import com.hqq.dao.GoodDao;
import com.hqq.dao.SaleDao;
import com.hqq.entity.Goods;
import com.hqq.entity.Sale;
import com.hqq.exception.NotEnoughException;
import org.apache.ibatis.jdbc.Null;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class BuyGoodsServiceImpl implements BuyGoodsService {

    private GoodDao goodDao;
    private SaleDao saleDao;


    @Transactional(
            propagation = Propagation.REQUIRED,
            isolation = Isolation.DEFAULT,
            readOnly = false,
            rollbackFor = {
                    NotEnoughException.class,NullPointerException.class
            }
    )
    @Override
    public void buyGoods(Integer buyId, Integer amount) {

        //如果不添加事务，那么给sale添加记录和库存减少是两个分开的操作，为了让这两个同时同步操作，需要给这个buyGoods方法增加事务
        //借助aop机制增加事务
        System.out.println("buy方法的开始============");

        //记录销售信息，往sale增加

        Sale sale = new Sale();
        sale.setGid(buyId);
        sale.setNums(amount);

        saleDao.insertSale(sale);
        //更新库存

        Goods goods = goodDao.searchGood(buyId);
        if (goods == null){
            throw new NullPointerException(buyId+"编号商品不存在");
        }else if (goods.getAmount() < amount){
            throw new NotEnoughException(buyId+"编号商品库存不足");
        }else {

            goods.setAmount(amount);
            goodDao.updateGoods(goods);

            System.out.println("buy方法的完成============");
        }




    }

    public void setGoodDao(GoodDao goodDao) {
        this.goodDao = goodDao;
    }

    public void setSaleDao(SaleDao saleDao) {
        this.saleDao = saleDao;
    }
}